const { Nuxt, Builder } = require("nuxt");

const app = require("express")();
const isProd = process.env.NODE_ENV === "production";
const port = process.env.PORT || 3000;

// 用指定的配置对象实例化 Nuxt.js
const config = require("../nuxt.config.js");
config.dev = !isProd;
const nuxt = new Nuxt(config);
const build = new Builder(nuxt).build();
app.get("/", function(req, res) {
  build
    .then(() => {
      return nuxt.renderRoute("/");
    })
    .then(({ html, error, redirected }) => {
      // html 类型为 string
      // 当显示 error 视图时，error 的值不为 null。error 对象的格式为:
      // { statusCode: 500, message: 'My error message' }
      // redirected is not false when redirect() has been used in data() or fetch()
      // 如果 `redirect` 方法已在 `asyncData` 或 `fetch` 方法中调用，redirected 的值非 false，其格式如下：
      // { path: '/other-path', query: {}, status: 302 }
      // console.log("html", html, error);
      res.send(html);
    });
});
app.get("/company", function(req, res) {
  build
    .then(() => {
      return nuxt.renderRoute("/company");
    })
    .then(({ html, error, redirected }) => {
      console.log("html", html, error);
      res.send(html);
    });
});

function listen() {
  // 服务端监听
  app.listen(port, "0.0.0.0");
  console.log("Server listening on `localhost:" + port + "`.");
}

listen();